package org.openanypcao.cs.core;

import java.io.BufferedWriter;
import java.io.DataInputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Map;

/**
 * 
 *作者：曹正标</p>
 *日期：2011-12-29</p>
 *功能：初始化httpurlconnection的tcp连接</p>
 */
public class HttpConnection {

	/**
	 * 
	 * 作  者：曹正标</p>
	 * 功  能：普通构造函数</p>
	 * 参  数：普通构造函数</p>
	 * 返回值：</p>
	 *
	 * 修改记录： </p>
	 * 修改日期：</p>
	 * 修改人：</p>
	 * 修改概述：</p>
	 */
	public HttpConnection() {
	}
	
	/**
	 * 
	 * 作  者：曹正标</p>
	 * 功  能：连接doGet方法</p>
	 * 参  数：</p>
	 * @param requestPath	：request路径</p>
	 * @param params		：参数(Map<String,String[]>)</p>
	 * @throws IOException	：抛出IOException异常</p>
	 * 返回值：</p>
	 * @return HttpURLConnection
	 * 修改记录： </p>
	 * 修改日期：</p>
	 * 修改人：</p>
	 * 修改概述：</p>
	 */
	public static HttpURLConnection doGet(String requestPath, Map<String, String[]> params) throws IOException{
		StringBuilder builder = new StringBuilder(requestPath);
		
		//解析参数
		if(params != null && params.size() > 0){
			if(requestPath.indexOf("?") == -1){
				builder.append("?");
			}else if(!requestPath.endsWith("&")){
				builder.append("&");
			}
			String paramKey = null;
			String[] paramValues = null;
			for(Map.Entry<String, String[]> e : params.entrySet()){
				paramKey = e.getKey();
				paramValues = e.getValue();
				if(paramValues != null && paramValues.length > 0){
					for(String s : paramValues){
						builder.append(paramKey);
						builder.append("=");
						builder.append(URLEncoder.encode(s, GeneralConstant.DEFAULT_ENCODE));
						builder.append("&");
					}
				}
			}
			builder.delete(builder.length()-1, builder.length());
		}
		
		//创建并启动连接
		URL url = new URL(builder.toString());
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setConnectTimeout(GeneralConstant.DEFAULT_CONNECT_TIMEOUT);
		connection.setReadTimeout(GeneralConstant.DEFAULT_READ_TIMEOUT);
		connection.addRequestProperty("User-Agent", "Mozilla/5.0");
		connection.setRequestProperty("Charsert", GeneralConstant.DEFAULT_ENCODE);
		connection.connect();
		return connection;
	}
	
	
	/**
	 * 
	 * 作  者：曹正标</p>
	 * 功  能：发送简单文本form表单</p>
	 * 参  数：</p>
	 * @param requestPath
	 * @param params
	 * @throws IOException
	 * 返回值：</p>
	 * @return HttpURLConnection
	 * 修改记录： </p>
	 * 修改日期：</p>
	 * 修改人：</p>
	 * 修改概述：</p>
	 */
	public static HttpURLConnection doPost(String requestPath, Map<String, String[]> params) throws IOException{
		URL url = new URL(requestPath);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		try{
			connection.setConnectTimeout(GeneralConstant.DEFAULT_CONNECT_TIMEOUT);
			connection.setReadTimeout(GeneralConstant.DEFAULT_READ_TIMEOUT);
			connection.setDoOutput(true); 
			connection.setDoInput(true);
			connection.setUseCaches(false);
			connection.setRequestMethod("POST");
			connection.addRequestProperty("User-Agent", "Mozilla/5.0");
			connection.setRequestProperty("Charsert", GeneralConstant.DEFAULT_ENCODE);
	        connection.addRequestProperty("Content-Type", "application/x-www-form-urlencoded");
	        
	        //发送数据
			BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(connection.getOutputStream(), GeneralConstant.DEFAULT_ENCODE));
			StringBuilder buffer = new StringBuilder();
			if(params != null && params.size() > 0){
				String paramKey = null;
				String[] paramValues = null;
				for(Map.Entry<String, String[]> e : params.entrySet()){
					paramKey = e.getKey();
					paramValues = e.getValue();
					if(paramValues != null && paramValues.length > 0){
						for(String s : paramValues){
							buffer.append(paramKey);
							buffer.append("=");
							buffer.append(URLEncoder.encode(s, GeneralConstant.DEFAULT_ENCODE));
							buffer.append("&");
						}
					}
				}
				buffer.delete(buffer.length()-1, buffer.length());
			}
			writer.write(buffer.toString());
			writer.flush();
			writer.close();
			
		}catch(ConnectException ce){
			ce.printStackTrace();
		}
		return connection;
		
	}
	

	/**
	 * 
	 * 作  者：曹正标</p>
	 * 功  能：发送复杂form表单，包含文件的表单</p>
	 * 参  数：</p>
	 * @param requestPath	：request路径</p>
	 * @param params		：参数(Map<String,String[])</p>
	 * @param paramFiles	：文件列表</p>
	 * @throws IOException	：抛出IOException异常</p>
	 * 返回值：</p>
	 * @return HttpURLConnection
	 * 修改记录： </p>
	 * 修改日期：</p>
	 * 修改人：</p>
	 * 修改概述：</p>
	 */
	public static HttpURLConnection doMultipartPost(String requestPath, Map<String, String[]> params, Map<String, File[]> paramFiles) throws IOException{
		String BOUNDARY="---------------------------7db1ea254054a";
		URL url = new URL(requestPath);
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		connection.setConnectTimeout(GeneralConstant.DEFAULT_CONNECT_TIMEOUT);
		connection.setReadTimeout(GeneralConstant.DEFAULT_READ_TIMEOUT);
		connection.setDoOutput(true);
		connection.setDoInput(true);
		connection.setUseCaches(false);
		connection.setRequestMethod("POST");
		connection.addRequestProperty("User-Agent", "Mozilla/5.0");
		connection.setRequestProperty("Charsert", GeneralConstant.DEFAULT_ENCODE);
        connection.addRequestProperty("Content-Type", "multipart/form-data; boundary="+BOUNDARY);
        OutputStream writer = new DataOutputStream(connection.getOutputStream());
		byte[] end_data = ("\r\n--" + BOUNDARY + "--\r\n").getBytes();// 定义最后数据分隔线
		
		//设置form表单信息数据
		if(params != null && params.size() > 0){
			String paramKey = null;
			String[] paramValues = null;
			StringBuilder builder = new StringBuilder();
			for(Map.Entry<String, String[]> e : params.entrySet()){
				paramKey = e.getKey();
				paramValues = e.getValue();
				if(paramValues != null && paramValues.length > 0){
					for(String s : paramValues){
						builder.append("--");
						builder.append(BOUNDARY);
						builder.append("\r\n");
						builder.append("Content-Disposition: form-data;name=\""+paramKey+"\"\r\n");
						builder.append("\r\n");
						builder.append(URLEncoder.encode(s, GeneralConstant.DEFAULT_ENCODE));
						builder.append("\r\n");
					}
				}
			}
			byte[] data = builder.toString().getBytes();  
			writer.write(data);
		}
		
		//设置form表单文件数据
		if(paramFiles != null && paramFiles.size() > 0){
			String paramKey = null;
			File[] paramValues = null;
			for(Map.Entry<String, File[]> e : paramFiles.entrySet()){
				paramKey = e.getKey();
				paramValues = e.getValue();
				if(paramValues != null && paramValues.length > 0){
					for(File f : paramValues){
						StringBuilder builder = new StringBuilder();
						builder.append("--");
						builder.append(BOUNDARY);
						builder.append("\r\n");
						builder.append("Content-Disposition: form-data;name=\""+paramKey+"\";filename=\""+ f.getName() + "\"\r\n");    
						builder.append("Content-Type:application/octet-stream\r\n\r\n");
						byte[] data = builder.toString().getBytes();  
						writer.write(data);  
						DataInputStream intmp = new DataInputStream(new FileInputStream(f));  
						int bytes = 0;  
						byte[] bufferOut = new byte[8192];  
						while ((bytes = intmp.read(bufferOut)) != -1) {  
							writer.write(bufferOut, 0, bytes);  
						}  
						writer.write("\r\n".getBytes()); //多个文件时，二个文件之间加入这个  
						intmp.close();
					}
				}
			}
		}
		writer.write(end_data);
		
		writer.flush();
		writer.close();
		
		return connection;
	}
	
}
